package com.yangyang.androidconnect.controller;

import android.content.Context;
import android.os.Environment;

import com.yangyang.androidconnect.common.ApiResult;
import com.yanzhenjie.andserver.annotation.PostMapping;
import com.yanzhenjie.andserver.annotation.RequestParam;
import com.yanzhenjie.andserver.annotation.RestController;
import com.yanzhenjie.andserver.http.multipart.MultipartFile;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;

import java.io.File;

@RestController
public class UploadController {

    @PostMapping(path = "/upload")
    public ApiResult upload(@RequestParam(name = "file") MultipartFile file, Context context) throws Exception {
        File downloadsDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);

        // 处理文件名冲突
        String originalFilename = file.getFilename();
        String fileName = originalFilename;
        File destFile = new File(downloadsDir, fileName);

        int counter = 1;
        while (destFile.exists()) {
            String nameWithoutExt = originalFilename.substring(0, originalFilename.lastIndexOf('.'));
            String ext = originalFilename.substring(originalFilename.lastIndexOf('.'));
            fileName = nameWithoutExt + " (" + counter + ")" + ext;
            destFile = new File(downloadsDir, fileName);
            counter++;
        }
        file.transferTo(destFile);

        return ApiResult.ok("上传成功", "文件保存为: " + fileName);
    }

}